import React, { Component } from "react";
import {
  StyleSheet,
  Dimensions,
  TouchableOpacity,
  View,
  Vibration,
  BackAndroid,
  BackHandler,
  ToastAndroid,
  Image,
} from "react-native";
import Modal from "react-native-modal";
import {
  Container,
  Fab,
  Header,
  Toast,
  Root,
  Badge,
  List,
  Spinner,
  ListItem,
  Thumbnail,
  ActionSheet,
  Text,
  Title,
  Icon,
  Left,
  Body,
  Right,
  Button,
  Card,
  CardItem
} from "native-base";

import {
  MapView,
  MapTypes,
  Geolocation,
  Overlay
} from "react-native-baidu-map";
import * as Animatable from 'react-native-animatable';
// MyCustomComponent = Animatable.createAnimatableComponent(MyCustomComponent);
const { height, width } = Dimensions.get("window");
const { Marker, Arc, Circle, Polyline, Polygon, InfoWindow } = Overlay;
const DURATION = 2000
const PATTERN = [1000, 2000, 3000]
const config = require('../server/config')
const request = require('../server/request')
var BUTTONS = [
  { text: 100, icon: "md-walk", iconColor: "#00b894" },
  { text: 500, icon: "md-walk", iconColor: "#00cec9" },
  { text: 1000, icon: "md-walk", iconColor: "#fdcb6e" },
  { text: 1500, icon: "md-walk", iconColor: "#e84393" },
  { text: 2000, icon: "md-walk", iconColor: "#d63031" },
  { text: 0, icon: "logo-sass", iconColor: "#000" },
  { text: 5, icon: "logo-sass", iconColor: "#000" },
  { text: 10, icon: "logo-sass", iconColor: "#000" },
  { text: 20, icon: "logo-sass", iconColor: "#000" },
  { text: 50, icon: "logo-sass", iconColor: "#000" },
  { text: 15000, icon: "logo-sass", iconColor: "#000" },



];
var DESTRUCTIVE_INDEX = 3;
var CANCEL_INDEX = 4;
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      zoom:18,
      province:"",
      district:"",
      address: "",
      city: "",
      streetName: "",

      longitude: 0,
      latitude: 0,

      cityCode: "289",

      clicked: {text:1500},
      active: false,
      visible: false,
      longitude2:0,
      latitude2:0,
      makerVisible:false,
      routeVisible:false,
      allData:[{
        latitude: 40.006901,
        longitude: 116.097972
      },
      {
        latitude: 40.006901,
        longitude: 116.097972
      }],
      center:{
        latitude:0,
        longitude:0
      },
      //俩点间距离
      maxDistance:0,
      isModalVisible: false,

      isPrompt:true
    };
    this.showInfo = this.showInfo.bind(this);
    this.loadRoute = this.loadRoute.bind(this)
    this.loadRouteData = this.loadRouteData.bind(this)
    this.loadData = this.loadData.bind(this)
  }
 
  //获取百度路线规划节点数据
  loadRouteData = () => {
    // alert(1)
    let url = config.api.route
    let self = this
    let arrs
    let allarrs=[]
    let data=''
    request
    .get(url, {
      origin:`${self.state.latitude},${self.state.longitude}`,
      destination:`${self.state.latitude2},${self.state.longitude2}`,
      ak:"GbLFKhL6jVei63ZnDdrYV3vWntOSxP53"
    })
    .then(function(responData) {
      if (responData.status == 0) {
       console.log(responData.result.routes[0])
       arrs = responData.result.routes[0].steps
       arrs.map((v) =>{
         data += v.path
       })
       arrs = data.split(";");
       arrs.map((v) => {
         let list = v.split(",")
         let obj={longitude: parseFloat(`${list[0]}`),latitude:parseFloat(`${list[1]}`)}
         allarrs.push(obj)
       })
       self.setState({
         allData:allarrs,
         maxDistance:responData.result.routes[0].distance
       })
       if(self.state.clicked.text < responData.result.routes[0].distance){
        Toast.show({
          text: '警告⚠ 已出安全范围',
          buttonText: "确认",
          duration: 3000,
          position: "bottom",
        })
       }
      }
    })
    .catch(err => {
      console.log("错误", err);
    })
  }
  //渲染路线
  loadRoute = () => {
    let self = this

    let address = self.state.address
    if(!address){
      Toast.show({
        text: '请先获取亲人位置信息',
        buttonText: "确认",
        duration: 3000,
        position: "bottom",
        type:"danger"
      })
      return
    }
    self.setState({
      zoom:16,
      routeVisible:true,
      center:{
        latitude:self.state.latitude,
        longitude:self.state.longitude
      }
    })
    // this.loadRouteData()
  }

  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    this.setState = (state,callback)=>{
      return;
    };
  }
  onBackAndroid = () => {
    if (this.props.navigation.isFocused()) {
      if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) { 
       //最近2秒内按过back键，可以退出应用
       return false
      } else{
        this.lastBackPressed = Date.now(); 
        ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT); 
        ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
         return true; 
      }
   }
  };
  //获取亲人定位数据
  loadData = () => {
    // alert(2)
    let url = config.api.base
    let self = this
    let arrs
    request.get(url).then(res => {
      if(res.data){
        let data = res.data
        console.warn(data)
        arrs = data.split(" ")

        let strLatitude1 = arrs[7]
        let strLongitude2 = arrs[8]
        let la1='',la2='', lon1='',lon2='';

        for(let i=0; i<=1; i++){
          la1 += strLatitude1[i]
        }
        for(let i=2; i<=8; i++){
          la2 += strLatitude1[i]
        }

        for(let i=0; i<=2; i++){
          lon1 += strLongitude2[i]
        }
        for(let i=3; i<=9; i++){
          lon2 += strLongitude2[i]
        }
        // console.warn(la1,la2)
        // console.warn(lon1,lon2)

        console.warn(arrs)
          self.setState({
            longitude2: parseFloat((parseFloat(lon1) + parseFloat(lon2)/60 + 0.013239).toFixed(6)),
            latitude2:  parseFloat((parseFloat(la1) + parseFloat(la2)/60 + 0.00709).toFixed(6))
          })
      }else{
        alert(1)
      }
    })
    .catch(err => {
      console.log(err)
    })
    
  }
 
  //显示亲人所在位置
  findView(){
    this.loadData()
    let self = this
    let latitude2 = self.state.latitude2
    let longitude2 = self.state.longitude2
    // debugger
    if(latitude2 ==0 ||longitude2 ==0){
      Toast.show({
        text: '请先开启设备',
        buttonText: "确认",
        duration: 3000,
        position: "bottom",
        type:"danger"
      })
      return
    }else{
      Geolocation.reverseGeoCode(latitude2,longitude2)
    .then(data => {
      // console.warn(data)
      console.log(data)

    self.setState({
      province:data.province,
      city:data.city,
      district:data.district,
      address:data.poiList[0].address,
      streetName:data.poiList[0].name,
      makerVisible:true,
      zoom:17,
      center:{
        longitude:self.state.longitude2,
        latitude:self.state.latitude2
      }
    })
    })
    .catch(e =>{
    console.warn(e, 'error');
    }) 
    Toast.show({
      text: '已获取亲人位置(在指定范围)',
      buttonText: "确认",
      duration: 3000,
      position: "bottom",
      // type:"warning"
    })
    this.loadRouteData()
    }
    
  }
  //获取自己位置信息
  privateRefresh() {
    // alert(1)
    let self = this;
    // setInterval(() => {
      Geolocation.getCurrentPosition()
      .then(data => {
        console.log("getCurrentPosition", data);
        self.setState({
          // address: data.address,
          city: data.city,
          longitude: data.longitude,
          latitude: data.latitude,
          center:{
            longitude:data.longitude,
            latitude:data.latitude
          }
        });
      })
      .catch(e => {
        console.warn(e, "error");
      });
    // }, 500);
  }
  //测试弹框
  showInfo() {
    this.setState({
      visible: true
    });
  }
  _toggleModal = () =>{
    let address = this.state.address
    if(!address){
      Toast.show({
        text: '请先获取亲人位置信息',
        buttonText: "确认",
        duration: 3000,
        position: "bottom",
        type:"danger"
      })
      return
    }

    this.setState({ isModalVisible: !this.state.isModalVisible });
  }
  componentDidMount() {
    this.privateRefresh()
    this.loadData()
    this.loadRouteData()
   
}

  render() {
    console.warn(this.state.latitude2,this.state.longitude2)
    const { infoWindowProps } = this.state;
    let latitude = this.state.latitude;
    let longitude = this.state.longitude;
    // console.warn("Overlay", Overlay);
    // console.log(this.state.maxDistance)
    let maxDistance = this.state.maxDistance
    // console.warn(maxDistance)
    let maxRange = this.state.clicked.text
    if(maxDistance > maxRange){
      index = true
      if(this.state.isPrompt){
        // alert(11)
      Vibration.vibrate(PATTERN, true)
      
      }else{
        Vibration.cancel()
      }
     

    }else{
      index = false
    }
    return (
      <Root>
        {!this.state.longitude? <Spinner />:
        
        <Container>
        <Modal isVisible={this.state.isModalVisible}>
          <View style={{ flex: 1 }}>
          <Card>
            <CardItem>
              <Left>
                <Thumbnail source={{uri: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1554920259134&di=24c72fbdd5f2e720df5eabfadb11ff14&imgtype=0&src=http://b-ssl.duitang.com/uploads/item/201509/19/20150919161113_sPjdT.jpeg"}} />
                <Body>
                  <Text>NativeBase</Text>
                  <Text note>GeekyAnts</Text>
                </Body>
              </Left>
              <Right>
              <Button  onPress={this._toggleModal} info transparent>
                  <Icon  name="md-backspace"  style={{ fontSize: 30}} />
                </Button>
              </Right>
            </CardItem>
              <CardItem><Icon active name="logo-googleplus" />
              <Text>{this.state.province}</Text>
             </CardItem>
             <CardItem><Icon active name="logo-googleplus" />
              <Text>{this.state.city}</Text>
             </CardItem>
             <CardItem><Icon active name="logo-googleplus" />
              <Text>{this.state.district}</Text>
             </CardItem>
             <CardItem><Icon active name="logo-googleplus" />
              <Text>{this.state.address}</Text>
             </CardItem>
             <CardItem><Icon active name="logo-googleplus" />
              <Text>{this.state.streetName}</Text>
             </CardItem>
            <CardItem>
            <Left>
                <Button transparent info>
                  <Icon active name="ios-person" />
                  <Text>本人：{this.state.longitude}</Text>
                </Button>
              </Left>
              <Right>
              <Button transparent info>
                  <Icon active name="ios-person" />
                  <Text>{this.state.latitude}</Text>
                </Button>
              </Right>
            </CardItem>
            <CardItem>
            <Left>
                <Button transparent info>
                  <Icon active name="ios-pin" />
                  <Text>亲人：{this.state.longitude2}</Text>
                </Button>
              </Left>
              <Right>
              <Button transparent info>
                  <Icon active name="ios-pin" />
                  <Text>{this.state.latitude2}</Text>
                </Button>
              </Right>
            </CardItem>
          </Card>
           
          </View>
        </Modal>
          <Header
            style={{ backgroundColor: "#fff" }}
            androidStatusBarColor="#00cec9"
          >
            <Body
              style={{ flexDirection: "row", justifyContent: "flex-start" }}
            >
            <Animatable.View animation="zoomIn" direction="normal">
            <TouchableOpacity onPress={this._toggleModal}>
            <Badge style={{ marginRight: 20, backgroundColor: "#00cec9",flexDirection:'row',alignItems:'center' }}>
              <Icon
                  name="ios-pin"
                  style={{color: "#fff",fontSize:23,marginRight:3,marginLeft: 3, }}
                />
                <Text>{this.state.city} </Text>
                <Text>{index} </Text>
              </Badge>
            </TouchableOpacity>
            </Animatable.View>
            
            {
              index&&this.state.isPrompt? 
              <Animatable.View animation="swing" easing="ease-out" duration={500} iterationCount="infinite" style={{ textAlign: 'center' }}>
              <TouchableOpacity onPress={() =>this.setState({isPrompt:false})}>
              <Icon
                  name="ios-notifications"
                  style={{ fontSize: 20, color: "#ff7675" }}
              />
              </TouchableOpacity>
              </Animatable.View>:null
            }
            </Body>
            <Right>
            <Button
                transparent
                onPress={()=>{this.findView()}}
              >
            <Animatable.Text animation="rotate"  duration={5000} easing="ease-out" iterationCount="infinite" style={{ textAlign: 'center' }}>
            <Icon
                name="ios-navigate"
                style={{ fontSize: 33, color: "#636e72" }}
            />
            </Animatable.Text>
              </Button>
            <Animatable.View animation="zoomIn" direction="normal">
            <Button
                transparent
                // onPress={()=>{this.loadRoute()}}
                onPress={() => this.props.navigation.navigate("SettingsScreen")}
              >
                <Icon
                  name="ios-log-in"
                  style={{ fontSize: 33, color: "#00cec9" }}
                />
              </Button>
            </Animatable.View>
             
            </Right>
          </Header>
          <MapView
            style={{ flex: 1 }}
            width={width}
            zoom={this.state.zoom}
            trafficEnabled={true}
            zoomControlsVisible={false}
            mapType={MapTypes.NORMAL}
            center={{
              longitude: this.state.center.longitude,
              latitude: this.state.center.latitude
            }}
            onMapClick={() => {this.loadData()}}
            onMarkerClick={() =>{

              Toast.show({
                text: `你所属位置 ${this.state.longitude}, ${this.state.latitude}`,
                buttonText: "确认",
                duration: 3000,
                position: "bottom"
              })
              this.privateRefresh()

            }
             
            }
          >
            <Marker
              location={{
                longitude: this.state.longitude,
                latitude: this.state.latitude
              }}
            
              perspective={true}
            />
            {
              this.state.makerVisible?<Marker
              location={{
                longitude: this.state.longitude2,
                latitude: this.state.latitude2
              }}
            />:null
            }
            {
              this.state.routeVisible? <Polyline points={this.state.allData}/>:null
            }
           
            <Circle
              center={{
                longitude: this.state.longitude,
                latitude: this.state.latitude
              }}
              radius={this.state.clicked.text}
              fillColor="16777215"
              stroke={{ width: 3, color: "AA000000" }}
            />
            
          </MapView>
          {/* </View> */}
          <Animatable.View animation="bounceInUp" direction="normal">
        </Animatable.View>

          <Fab
            active={this.state.active}
            direction="up"
            containerStyle={{}}
            style={{ backgroundColor: "#00cec9" }}
            position="bottomRight"
            onPress={() => this.setState({ active: !this.state.active })}
          >
            <Icon name="ios-options" />
            <Button style={{ backgroundColor: "#fdcb6e" }} onPress={() =>{this.setState({isPrompt:true})}}>
              <Icon name="ios-notifications" />
            </Button>
            <Button
              style={{ backgroundColor: "#0984e3" }}
              onPress={() => {
                ActionSheet.show(
                  {
                    options: BUTTONS,
                    cancelButtonIndex: CANCEL_INDEX,
                    // destructiveButtonIndex: DESTRUCTIVE_INDEX,
                    title: "设置最大活动范围"
                  },
                  buttonIndex => {
                    this.setState({ clicked: BUTTONS[buttonIndex] });
                    Toast.show({
                      text: '最大活动范围以更新',
                      buttonText: "确认",
                      duration: 3000,
                      position: "top",
                      type:"success"
                    })
                  }
                );
                this.privateRefresh();
              }}
            >
              <Icon name="ios-settings" />
            </Button>
            <Button style={{ backgroundColor: "#6c5ce7" }} onPress={()=>{this.loadRoute()}}>
              <Icon name="md-paper-plane" />
            </Button>
          </Fab>
          
        </Container>
        }
      </Root>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  }
});
